<template>
  <el-dialog :visible.sync="visible"
             :title="title"
             width="75%"
             v-loading.fullscreen.lock="loading"
             :before-close="modalClose"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="submitData"
             label-position="right"
             label-width="180px"
             ref="formModelRef"
             :rules='formModelRules'>
      <el-form-item label="通知名称:" prop="title">
        <el-input placeholder="请输入通知名称"
                  v-model="submitData.title"
                  class="w-300"
                  clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="通知内容:" class="is-required">
        <el-radio-group v-model="submitData.noticeType">
          <el-radio :label="1">文件内容</el-radio>
          <el-radio :label="2">自定义内容</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="submitData.noticeType===1" prop="url"
                    :rules="submitData.noticeType===1?formModelRules.url:[{required: false}]">

        <el-upload :action="fileLogoUploadAction"
                   :max-size="fileMaxSize"
                   class="avatar-uploader"
                   :show-file-list="false"
                   accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg,.doc,.pdf"
                   :before-upload="beforeAvatarUpload"
                   :on-exceeded-size="showError"
                   :on-success="uploadLogoSuccess">
          <img v-if="submitData.url" :src="submitData.url" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-button type="success" @click="handleDownLoad">下载文件</el-button>
        <p style="color: #aa1111">* 仅支持word,PDF，图片文件格式</p>
      </el-form-item>
      <el-form-item v-if="submitData.noticeType===2" prop="content"
                    :rules="submitData.noticeType===2?formModelRules.content:[{required: false}]">
        <div ref="editor"
             class="editor">
          <vue-neditor-wrap :destroy="false"
                            v-model="submitData.content"
                            :config="myConfig"></vue-neditor-wrap>
        </div>
      </el-form-item>
      <el-form-item label="接收公司：" prop="companyId">
        <el-select v-model="submitData.companyId"
                   class="w-300"
                   placeholder="选择接收公司">
          <el-option v-for="item in companyList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>

      </el-form-item>

      <el-form-item label="接收门店:" class="is-required">
        <el-radio-group v-model="submitData.distributionType">
          <el-radio :label="1">全部门店</el-radio>
          <el-radio :label="2">指定门店</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="submitData.distributionType==2">
        <el-select v-model="chooseStore"
                   value-key="id"
                   filterable
                   remote
                   clearable
                   reserve-keyword
                   placeholder="请输入门店关键字"
                   :remote-method="searchMethod"
                   :loading="searchLoading"
                   class="w-300">
          <el-option v-for="item in searchStoreList"
                     :key="item.id"
                     :label="item.name"
                     :value="item">
          </el-option>
        </el-select>

        <el-button type="primary"
                   @click="handleAddStore()">新 增
        </el-button>
      </el-form-item>
      <el-form-item v-if="submitData.distributionType==2">
        <element-table :columns="columns"
                       :data="tableData">
          <template v-slot:option="{row,index}">
            <el-button type="danger"
                       @click="handleDelStore(index)">删除
            </el-button>
          </template>
        </element-table>

      </el-form-item>
      <el-form-item label="是否需要考核：" class="is-required">
        <el-radio-group v-model="submitData.isAssess">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-if="submitData.isAssess==1">

        <el-form-item label="考核名称：" prop="assessName"
                      :rules="submitData.isAssess==1?formModelRules.assessName:[{required: false}]">
          <el-input placeholder="请输入考核名称"
                    v-model="submitData.assessName"
                    class="w-300"
                    clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="考核题目：" class="is-required">
          <el-button type="primary" @click="handleAddQuestion">增加题目</el-button>
          <p style="color: #aa1111">* 需要填写的部分可用（）或___占位！</p>
        </el-form-item>
        <el-form-item v-for="(item,index) in submitData.managementAssessQuestions" :key="index">
          <p>题目{{ index + 1 }}:</p>
          <el-input v-model="item.itemName"
                    clearable
                    type="textarea"
                    style="width: 380px"
                    placeholder="请输入题目"/>
          <el-button type="primary" @click="handleAddOption(index)">增加答案</el-button>
          <el-button type="danger" @click="handleDelQuestion(index)">删除题目</el-button>
          <div v-for="(its,idx) in item.itemValue" :key="idx"
               style="display: flex;flex-direction: row;margin-top: 20px">
            <el-input v-model="item.itemValue[idx]"
                      clearable
                      style="width: 380px"
                      type="textarea"
                      placeholder="请输入对应答案"></el-input>

            <el-button type="danger" @click="handleDelOption(index,idx)" style="margin-left: 5px">删除答案</el-button>
          </div>
        </el-form-item>
        <el-form-item label="考核完成奖励：" prop="assessFinishAward"
                      :rules="submitData.isAssess==1?formModelRules.assessFinishAward:[{required: false}]">
          <el-input placeholder="考核完成奖励"
                    v-model="submitData.assessFinishAward"
                    class="w-300"
                    clearable>
            <el-button slot="append">元</el-button>
          </el-input>
        </el-form-item>

        <el-form-item label="考核有效期：" prop="times"
                      :rules="submitData.isAssess==1?formModelRules.times:[{required: false}]">
          <el-date-picker v-model="submitData.times"
                          type="daterange"
                          value-format="yyyy-MM-dd"
                          clearable
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          @change="changeTime">
          </el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <p align="center">
      <el-button type="primary" v-prevent-re-click
                 @click="handleSubmit">确 认
      </el-button>
      <el-button @click="modalClose"
                 style="margin-left: 8px">取 消
      </el-button>
    </p>

  </el-dialog>
</template>

<script>
import VueNeditorWrap from "vue-neditor-wrap";
import ElementTable from "../../../../base/ElementTable";

export default {
  name: "updateDiaog",
  props: {
    dataObj: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      title: '新 增',
      loading:false,
      submitData: {
        title: '',
        noticeType: 1,
        companyId: '',
        distributionType: 1,
        content: '',
        url: '',
        isAssess: 1,
        assessName: '',
        assessFinishAward: '',
        assessStartString: '',
        assessEndString: '',
        managementAssessQuestions: [],
        hospitalIds: [],
        times: [],
        id: ''
      },
      fileLogoUploadAction: this.api.file.upload,
      fileMaxSize: 1024 * 50,
      myConfig: {
        // 你的UEditor资源存放的路径,相对于打包后的index.html
        UEDITOR_HOME_URL: this.api.uEditorHomeUrl,
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: '418',
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 关闭自动保存
        enableAutoSave: false,
        scaleEnabled: true
      },
      searchLoading: false,
      chooseStore: '',
      searchStoreList: [],//搜索店铺列表
      companyList: [],//公司列表
      columns: [
        {
          label: '门店名称',
          prop: 'name',
          align: "center",
          width: 200
        }, {
          label: '门店地址',
          prop: 'address',
          align: "center"
        }, {
          label: '店长',
          prop: 'doctorManage.nickName',
          align: 'center',

        }, {
          label: '联系方式',
          prop: 'phone',
          align: 'center',

        }, {
          label: '操作',
          prop: 'option',
          align: 'center',
          isSlot: true,
          width: 200
        }
      ],
      tableData: [],

      formModelRules: {
        title: [{required: true, message: '请输入通知名称', trigger: 'blur'}],
        url: [{required: true, message: '请上传文件', trigger: 'blur'}],
        content: [{required: true, message: '请输入内容', trigger: 'blur'}],
        companyId: [{required: true, message: '请选择接收公司', trigger: 'change'}],
        assessName: [{required: true, message: '请输入考核名称', trigger: 'blur'}],
        assessFinishAward: [{required: true, message: '请输入考核完成奖励', trigger: 'blur'}],
        times: [{required: true, message: '请选择考核有效期', trigger: 'blur'}],
      }

    }
  },
  created() {
    if (this.dataObj.id) {
      this.title = '编 辑'
      this.submitData.id = this.dataObj.id
      this.getManagementNoticeDetail()
    } else {
      this.title = '新 增'
    }
    this.getCompanyList()
  },
  methods: {
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    //获取详情
    getManagementNoticeDetail() {
      this.post(this.api.promote.getManagementNoticeDetail, {
        id: this.dataObj.id
      }).then((res) => {
        if (res.data.code === '200') {
          this.submitData = Object.assign(this.submitData, res.data.object)
          if (res.data.object.hospitals) {
            this.tableData = res.data.object.hospitals
          }
          try {
            this.submitData.managementAssessQuestions.forEach((item, index) => {
              this.$set(this.submitData.managementAssessQuestions[index], 'itemValue', item.itemValue.split(','))
            })
            let times = []
            times[0] = this.submitData.assessStartString
            times[1] = this.submitData.assessEndString
            this.$set(this.submitData, 'times', times)
          } catch (e) {

          }
        }
      })
    },
    //提交
    handleSubmit() {
      this.$refs.formModelRef.validate(async (valid) => {
        if (valid) {

          if (this.submitData.distributionType == 2 && this.tableData.length === 0) {
            this.$message.error('请添加门店')
          } else {
            if (this.submitData.noticeType == 1) {
              this.submitData.content = ''
            } else if (this.submitData.noticeType == 2) {
              this.submitData.url = ''
            }
            let newData = JSON.parse(JSON.stringify(this.submitData));
            if (this.tableData.length > 0) {
              let companyIds = this.tableData.map(item => item.id);
              this.$set(newData, 'hospitalIds', companyIds)
            }
            if (this.submitData.isAssess == 1) {
              try {
                newData.managementAssessQuestions.forEach((item, index) => {
                  newData.managementAssessQuestions[index].itemValue = item.itemValue.toString()
                })
              } catch (e) {

              }

            }
            this.loading=true
            this.post(this.api.promote.saveNotice, newData).then(res => {
              if (res.data.code === '200') {
                this.post(this.api.promote.sendNoticeMsg, {
                  id: res.data.object.id
                }).then(res => {
                  this.loading=false
                  if (res.data.code === '200') {
                    this.$message.success('发布成功')
                    this.modalClose()
                    this.$parent.getList()
                  }
                })

              }
            })
          }
        }
      })


    },
    changeTime(item) {
      if (item) {
        this.submitData.assessStartString = item[0]
        this.submitData.assessEndString = item[1]
      } else {
        this.submitData.assessStartString = ''
        this.submitData.assessEndString = ''
      }
    },

    beforeAvatarUpload(file) {
      let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp', 'application/msword', 'application/pdf']
      const isJPG = types.includes(file.type)
      if (!isJPG) {
        this.$message.error('上传附件必须是JPG/JPEG/GIF/PNG/BMP/PDF/word 格式!');
      }
      return isJPG;
    },
    //上传图片错误
    showError(file, fileList) {
      this.$Notice.warning({
        title: '文件大小超限',
        desc: "文件  " + file.name + " 太大，上传文件大小不能超过100M."
      });
    },
    //上传成功
    uploadLogoSuccess(res) {
      if (res.code === '200') {
        this.$message.success('上传成功');
        this.$set(this.submitData, 'url', res.object[0])
      } else {
        this.$message.error('上传失败');
      }
    },
    //下载文件
    handleDownLoad() {
      if (this.submitData.url) {
        // const el = document.createElement('a');
        // let fileName='通知文件'
        // el.style.display = 'none';
        // el.setAttribute('target', '_blank');
        // fileName && el.setAttribute('download', fileName);
        // el.href = this.submitData.url;
        // el.download = fileName;
        // document.body.appendChild(el);
        // el.click();
        // document.body.removeChild(el);
        const a = document.createElement('a')
        a.setAttribute('download', '文件名')
        a.setAttribute('target', '_blank')
        a.setAttribute('href', this.submitData.url)
        a.click()
      }

    },
    //搜索门店
    searchMethod(query) {
      if (query !== '') {
        let _this = this;
        _this.searchLoading = true; // 锁住
        this.post(this.api.promote.getFindHospital, {
          name: query,
          pageIndex: 0,
          pageSize: 10
        }).then(res => {
          if (res.data.code === '200') {
            _this.searchLoading = false;
            _this.searchStoreList = res.data.object;
          }
        })

      } else {
        this.searchStoreList = [];
      }
    },
    //添加门店
    handleAddStore() {
      if (this.chooseStore) {
        let tableData = this.tableData;

        if (tableData.length > 0 && tableData.map(item => item.id).indexOf(this.chooseStore.id) !== -1) {
          this.$message.warning('门店已存在')
        } else {
          this.tableData.push(this.chooseStore)
        }

      } else {
        this.$message.warning('请选择门店')
      }
    },
    //删除门店
    handleDelStore(index) {
      this.tableData.splice(index, 1)
    },
    //增加题目
    handleAddQuestion() {
      this.submitData.managementAssessQuestions.push({
        itemName: '',
        itemValue: []
      })
    },
    //删除题目
    handleDelQuestion(index) {
      this.submitData.managementAssessQuestions.splice(index, 1)
    },
    //增加答案
    handleAddOption(index) {
      this.submitData.managementAssessQuestions[index].itemValue.push("")
    },
    //删除答案
    handleDelOption(index, idx) {
      this.submitData.managementAssessQuestions[index].itemValue.splice(idx, 1)
    },
    //查询公司
    getCompanyList() {
      this.post(this.api.company.companyList, {
        pageIndex: 0,
        pageSize: 100
      }).then(res => {
        if (res.data.code === '200') {
          this.companyList = res.data.object;
        }
      })
    }
  },
  components: {
    VueNeditorWrap,
    'element-table': ElementTable,
  }
}
</script>

<style scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 15px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
